package com.my.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

public interface TreeNode<T> {

    T nodeId();

    T parentId();

    void addChildren(List<? extends TreeNode<?>> children);

    List<? extends TreeNode<?>> children();

    /**
     * 获取所有叶子节点,可依据条件过滤
     *
     * @return 符合 filter 条件的叶子节点列表
     */
    default List<TreeNode<T>> allLeafNodes(Predicate<TreeNode<T>> filter) {
        List<TreeNode<T>> result = new ArrayList<>();
        collectLeafNodes(this, filter, result::add);
        return result;
    }

    /**
     * 递归收集叶子节点
     */
    static <T> void collectLeafNodes(TreeNode<T> node, Predicate<TreeNode<T>> filter, Consumer<TreeNode<T>> leftNodeCollector) {
        if (node.children() == null || node.children().isEmpty()) {
            if (filter == null || filter.test(node)) {
                leftNodeCollector.accept(node);
            }
        } else {
            for (TreeNode<?> child : node.children()) {
                @SuppressWarnings("unchecked")
                TreeNode<T> typedChild = (TreeNode<T>) child;
                collectLeafNodes(typedChild, filter, leftNodeCollector);
            }
        }
    }
}
